package jwanalytics.ejb.webhouse;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import jwanalytics.utils.date.BaseCalendar;

/** 
 * Analytics star schema model date dimension. Adapted from page 39 of
 * "Wiley  Sons - The Data Warehouse Toolkit. Second Edition" 
 * @TODO: rename to DateAndTimeFacade. */
@Stateless(name="DateAndTimeFacade")
public class DateAndTimeFacade implements DateAndTimeFacadeLocal {
	
	@PersistenceContext EntityManager entityManager;
	
	/** Range includes boundaries. */
	public String getFactCountsPerDateRange(int minDateId, int maxDateId) {
		DateDimension dateDimension = entityManager.find(DateDimension.class, 2);
		try {
			String fromEJBJARXML = getStartDate().toString();
			return "From ejb-jar.xml:"+fromEJBJARXML+". Also, a string is good enough for a start:"+dateDimension.getId()+", date:"+dateDimension.getDate();
		} catch (Exception e) {
			return "Error"+e;
		}
	}
	
	
	/** 
     * Will get the start date for the date_dimension table on our star schema for web analytics. On most examples this is 2005-01-01, feel free to change it. 
	 * By editing ejb-jar.xml. 
	 */
	public Date getStartDate() {
		try {
			InitialContext ic = new InitialContext();
			String fromEJBJARXML = (String)ic.lookup("java:comp/env/startDate");
			SimpleDateFormat sdf = new java.text.SimpleDateFormat("yy-mm-dd");
			return sdf.parse(fromEJBJARXML);
		} catch(Throwable t) {
			return new Date();
		}
	}
	
	/** Returns the index of a date on date_dimension table of star schema. */
	public Integer getDateDimensionKey(Date dateToFindKey) {
		return BaseCalendar.daysSpan(dateToFindKey, getStartDate());		
	}
	
	
	/** Returns the index of a date on date_dimension table of star schema. */
	public Integer getTimeOfDayDimensionKey(Date dateToFindKey) {
		return BaseCalendar.daysSpan(dateToFindKey, getStartDate());		
	}	
	
}
